
Boxing: Implicit conversion a value type to a reference type is called boxing. In boxing process, a value type is being allocated on the heap rather than the stack.
Unboxing: Explicit conversion of the same reference type (which is being created by boxing), back to a value type. In unboxing process, an unboxed value being allocated to a variable on the stack rather then the heap. Now given bellow the code and explain the code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using testForClass1;
namespace testFor
{
public class Program
{
static void Main(string[] args)
{
object obj = new object();
int myValue = 102;
obj = myValue; // Boxing
Console.WriteLine("Boxing Value : "+obj);
int myValueTwo =(int)obj;//Unboxing
Console.WriteLine("Unboxing Value : " + myValueTwo);
Console.Read();
}
}
}
Object is a C# base class. All class inherit by object class, now we create object class obj then int value assign the object. We know object is reference type and int is value type. When we assign the value type into reference type it called boxing. Again, when we reference type to assign it’s called unboxing.